<template>
  <a-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消"
  >
    <!-- 操作按钮区域 -->
    <div class="table-operator mt10">
      <a-popconfirm title="确定要批量清箱吗？清箱后无法恢复！" v-has="'cell:clear'" @confirm="cellClear()"
        ><a-button type="primary" icon="rest">批量清箱</a-button></a-popconfirm
      >
      <a-button type="primary" icon="plus" v-has="'cell:add'" @click="openBatchAddCellModal">批量新增</a-button>
      <a-button type="danger" icon="minus" v-has="'cell:delete'" @click="batchDelete">批量删除</a-button>
      <a-button type="danger" icon="lock" v-has="'cell:lock'" @click="allOpen">全开锁</a-button>
      <a-button type="success" icon="plus" v-has="'cell:add'" @click="openAddCellModal">新增</a-button>
    </div>

    <!-- table区域 -->
    <a-table
      ref="table"
      bordered
      size="middle"
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :scroll="{ x: 1200 }"
      @change="handleTableChange"
    >
      <template slot="cellType" slot-scope="text, record, index">
        <j-dict-select-tag
          v-if="record.isEdit"
          v-model="stash.cellType"
          style="width: 100px"
          placeholder="请选择"
          dictCode="cellType"
        />
        <template v-else>
          {{ filterDictText(cellTypeOptions, text) }}
        </template>
      </template>
      <template slot="cellStatus" slot-scope="text, record, index">
        <j-dict-select-tag
          v-if="record.isEdit"
          v-model="stash.cellStatus"
          style="width: 100px"
          placeholder="请选择"
          dictCode="cellStatus"
        />
        <template v-else>
          {{ filterDictText(cellStatusOptions, text) }}
        </template>
      </template>
      <template slot="openType" slot-scope="text, record, index">
        <j-dict-select-tag
          v-if="record.isEdit"
          v-model="stash.openType"
          style="width: 100px"
          placeholder="请选择"
          dictCode="openMode"
        />
        <template v-else>
          {{ filterDictText(openModaeOptions, text) }}
        </template>
      </template>
      <template slot="version" slot-scope="text, record, index">
        <a-input v-if="record.isEdit" v-model="stash.version"></a-input>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template slot="lockNum" slot-scope="text, record, index">
        <a-input v-if="record.isEdit" v-model="stash.lockNum"></a-input>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template slot="otherName" slot-scope="text, record, index">
        <a-input v-if="record.isEdit" v-model="stash.otherName"></a-input>
        <template v-else>
          {{ text.replace('区', '-') }}
        </template>
      </template>
      <template slot="cardNum" slot-scope="text, record, index">
        <a-input v-if="record.isEdit" v-model="stash.cardNum"></a-input>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template slot="fingerprint" slot-scope="text, record, index">
        <a-input v-if="record.isEdit" v-model="stash.fingerprint"></a-input>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template slot="face" slot-scope="text, record, index">
        <a-input v-if="record.isEdit" v-model="stash.face"></a-input>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template slot="vein" slot-scope="text, record, index">
        <a-input v-if="record.isEdit" v-model="stash.vein"></a-input>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <span slot="action" slot-scope="text, record, index">
        <a-button v-has="'cell:lock'" type="orange" size="small" icon="lock" class="ml5 mr5" @click="cellOpen(record)"
          >开锁</a-button
        >
        <a-button
          v-has="'cell:status'"
          type="success"
          size="small"
          icon="wifi"
          class="ml5 mr5"
          @click="refreshCell(record)"
          >状态</a-button
        >
        <a-button
          v-has="'cell:edit'"
          type="primary"
          size="small"
          icon="edit"
          class="ml5 mr5"
          v-if="!record.isEdit"
          @click="() => editCell(record, index)"
          >编辑</a-button
        >
        <span v-else>
          <a-button icon="check" type="primary" size="small" class="ml5 mr5" @click="() => save(record, index)"
            >保存</a-button
          >
          <a-button icon="close" type="orange" @click="() => cancel(record, index)" size="small" class="ml5 mr5"
            >取消</a-button
          >
        </span>
        <a-button
          v-has="'cell:delete'"
          type="danger"
          size="small"
          icon="minus"
          class="ml5 mr5"
          @click="batchDelete(record.id)"
          >删除</a-button
        >
      </span>
    </a-table>

    <cell-batch-add @refresh="afterAdd" ref="CellBatchAdd"></cell-batch-add>
    <cell-add @refresh="afterAdd" ref="CellAdd"></cell-add>
  </a-modal>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'
import { getAction, postAction, putAction, deleteAction } from '@/api/manage'
import CellBatchAdd from '@views/DeviceManage/Modal/CellBatchAdd'
import CellAdd from '@views/DeviceManage/Modal/CellAdd'
import Api from '@/api/DeviceManage/DeviceList'
export default {
  name: 'CellManage',
  mixins: [JeecgListMixin],
  components: { CellBatchAdd, CellAdd },
  data() {
    return {
      filterDictText,
      title: '格子信息',
      modalWidth: '80%',
      visible: false,
      url: {
        list: Api.cellList,
        edit: Api.cellEdit,
        deleteBatchCell: Api.deleteBatchCell
      },
      columns: [],
      disableMixinCreated: true,
      cellTypeOptions: [],
      cellStatusOptions: [],
      openModaeOptions: [],
      record: {},
      stash: {
        cellStatus: '',
        openType: ''
      },
      needRefreshMachine: false
    }
  },
  created() {
    this.columns = [
      {
        title: '格子类型',
        dataIndex: 'cellType',
        width: 110,
        scopedSlots: { customRender: 'cellType' }
      },
      {
        title: '格子状态',
        dataIndex: 'cellStatus',
        width: 120,
        scopedSlots: { customRender: 'cellStatus' }
      },
      {
        title: '开启方式',
        dataIndex: 'openType',
        width: 120,
        scopedSlots: { customRender: 'openType' }
      },
      {
        title: '版号',
        dataIndex: 'version',
        scopedSlots: { customRender: 'version' }
      },
      {
        title: '锁号',
        dataIndex: 'lockNum',
        scopedSlots: { customRender: 'lockNum' }
      },
      {
        title: '别名',
        dataIndex: 'otherName',
        scopedSlots: { customRender: 'otherName' }
      },
      {
        title: '关联卡编号',
        dataIndex: 'cardNum',
        scopedSlots: { customRender: 'cardNum' }
      },
      {
        title: '关联指纹',
        dataIndex: 'fingerprint',
        scopedSlots: { customRender: 'fingerprint' }
      },
      {
        title: '关联人脸',
        dataIndex: 'face',
        scopedSlots: { customRender: 'face' }
      },
      {
        title: '关联静脉',
        dataIndex: 'vein',
        scopedSlots: { customRender: 'vein' }
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 400,
        scopedSlots: { customRender: 'action' }
      }
    ]
  },
  methods: {
    // 初始化数据字典
    initDictConfig() {
      //初始化字典 - 格子类型
      initDictOptions('cellType').then(res => {
        if (res.success) {
          this.cellTypeOptions = res.result
        }
      })
      //初始化字典 - 格子状态
      initDictOptions('cellStatus').then(res => {
        if (res.success) {
          this.cellStatusOptions = res.result
        }
      })
      //初始化字典 - 格子开启方式
      initDictOptions('openMode').then(res => {
        if (res.success) {
          this.openModaeOptions = res.result
        }
      })
    },

    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData(undefined, { column: undefined })
    },

    cancel(record, index) {
      this.$set(this.dataSource[index], 'isEdit', false)
    },

    // 展示弹窗
    showModal(record) {
      this.record = record
      this.ipagination.current = 1
      this.visible = true
      this.queryParam.deviceId = record.deviceId
      this.searchData()
      this.initDictConfig()
    },

    // 删除or批量删除
    batchDelete(id) {
      if (!this.selectedRowKeys.length && !id) {
        this.$message.error('请选择至少一个格子')
      } else {
        let that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function() {
            let data = that.selectedRowKeys.length ? that.selectedRowKeys : [id]
            deleteAction(that.url.deleteBatchCell + data).then(res => {
              if (res.code === 200) {
                that.$message.success('删除成功')
                that.selectedRowKeys = []
                that.searchData()
                that.needRefreshMachine = true
              } else {
                that.$message.error(res.message)
              }
            })
          }
        })
      }
    },

    openBatchAddCellModal() {
      this.$refs['CellBatchAdd'].showModal(this.record)
    },

    openAddCellModal() {
      this.$refs['CellAdd'].showModal(this.record)
    },

    editCell(record, index) {
      this.$set(this.dataSource[index], 'isEdit', true)
      this.stash = { ...record }
    },
    save(record, index) {
      const criteria = Object.assign({}, record, this.stash)
      putAction(this.url.edit, criteria)
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.searchData()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleOk() {
      this.close()
    },
    handleCancel() {
      this.close()
    },

    close() {
      this.$emit('close')
      if (this.needRefreshMachine) {
        this.$emit('refresh')
      }
      this.visible = false
      this.disableSubmit = false
    },
    modalFormOk() {},

    // 刷新格子
    refreshCell(record) {
      const data = {
        id: record.id
      }
      getAction(Api.refreshCell, data).then(res => {
        this.$message.success(res.message)
        this.searchData()
      })
    },

    afterAdd() {
      this.searchData()
      this.needRefreshMachine = true
    },

    allOpen(){
      getAction(Api.allOpen + this.record.deviceId).then(res => {
        if (res.code === 200) {
          this.$message.success('全开锁成功')
        } else {
          this.$message.error(res.message)
        }
        this.searchData()
      })
    },

    // 开柜
    cellOpen(record) {
      let data = []
      if (record === 'all') {
        if (!this.selectedRowKeys.length) {
          this.$message.error('请选择一个格子')
          return
        } else {
          data = this.selectedRowKeys
        }
      } else {
        data.push(record.id)
      }

      postAction(Api.cellOpen, data).then(res => {
        if (res.code === 200) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
        this.searchData()
      })
    },

    searchData() {
      this.loadData(undefined, { column: [] })
    },

    // 清箱
    cellClear() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length === 0) {
        this.$message.error('请选择至少一个格子')
        return
      }
      postAction(Api.cellClear, this.selectedRowKeys).then(res => {
        this.$message.success(res.message)
        this.searchData()
      })
    }
  }
}
</script>

